package com.itheima.tcp4;

import com.itheima.tcp3.ServerReader;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Server {

    public static void main(String[] args) throws Exception {

        //简单的BS架构

        System.out.println("==========服务端启动==========");

        //1.创建一个服务端Socket对象，绑定9999端口，监听客户端连接
        ServerSocket ss = new ServerSocket(8080);


        //创建线程池
        ExecutorService pool = new ThreadPoolExecutor(3, 10, 10,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), new ThreadPoolExecutor.AbortPolicy());
        //主线程负责接受客户端的连接请求
        while (true) {

            //2.调用accept()方法，阻塞等待客户端连接，一旦有客户端连接会返回一个Socket对象
            Socket socket = ss.accept();

            //上线
            System.out.println("1个客户端连接成功！"+socket.getInetAddress().getHostAddress());

            /*//3.把这个Socket通信管道交给一个独立的子线程处理
            new ServerReader(socket).start();*/

            //3.把这个Socket通信管道包装成一个任务交给线程池处理
            pool.execute(new ServerReaderRunnable(socket));
        }

    }
}
